from django.db import models
from score.models import KnowledgePoint
from analysis.models import KnowledgeRelationship


class KnowledgeService:
    """知识点处理服务"""

    def find_related_knowledge_points(self, knowledge_point, relation_type=None):
        """查找关联知识点"""
        queryset = KnowledgeRelationship.objects.filter(
            source_knowledge=knowledge_point
        )

        if relation_type:
            queryset = queryset.filter(relationship_type=relation_type)

        return queryset.select_related('target_knowledge')

    def get_prerequisites(self, knowledge_point):
        """获取前置知识点"""
        return self.find_related_knowledge_points(
            knowledge_point, 'prerequisite'
        )

    def build_knowledge_tree(self, student, root_point=None):
        """构建知识点树形结构"""
        # 简化实现 - 返回扁平列表
        if root_point:
            points = KnowledgePoint.objects.filter(
                subject=root_point.subject
            )
        else:
            points = KnowledgePoint.objects.all()

        return points.select_related('subject')

    def suggest_knowledge_points(self, student, search_term):
        """根据搜索词推荐知识点"""
        return KnowledgePoint.objects.filter(
            models.Q(name__icontains=search_term) |
            models.Q(subject__name__icontains=search_term)
        )[:10]  # 限制返回数量